package com.jy.modules.cims.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.component.common.service.TCMmContractService;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.creditright.service.CreditDealService;
import com.jy.modules.cims.data.common.dto.TCMmContractDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditPackageDTO;
import com.jy.modules.cims.data.dto.ContractAllDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;

/**
 * @classname: TCMmContractController
 * @description: 定义  合约 控制层
 * @author:  dell
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmContract")
public class TCMmContractController extends CimsBaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmContractController.class);
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmContractService")
    private TCMmContractService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService serviceContract;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.deal.service.DealService")
    public DealService dealService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.creditright.service.CreditDealService")
    public CreditDealService creditDealService;
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate,HttpServletRequest request) throws AbaboonException {
        ModelAndView model = new ModelAndView();
       
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/paramManage/queryTCMmContract");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/paramManage/addTCMmContract");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/paramManage/addTCMmContract");
        }else if("toUpdate2".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/paramManage/updateTCMmContract");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.addObject("action", "view");
        	model.setViewName("cims/paramManage/updateTCMmContract");
        }else if("toSelectContract".equals(operate)){//跳转至选择合约页面
        	model.setViewName("cims/paramManage/selectTCMmContract");
        }else if("toSelectContractBuy".equals(operate)){//跳转至二次购买选择合约页面
        	model.setViewName("cims/creditManage/buy/selectTCMmContract");
        }else if("toBackCooperorgDealAdd".equals(operate)){//跳转至债权交易新增页面
        	String contractCode = this.getParameterString("contractCode");
        	model = serviceContract.queryAllDTO(contractCode);
        	model.setViewName("cims/creditDeal/addTCMmCooperorgDeal");
        }else if("toBackLoanDetailAdd".equals(operate)){//跳转至贷款交易新增页面
        	String contractCode = this.getParameterString("contractCode");
        	model = serviceContract.queryAllDTO(contractCode);
        	model.setViewName("cims/loanDealManage/addTCMmLoanDeal");
        }else if("toBackCooperorgDealUpdate".equals(operate)){//跳转至债权交易修改页面
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String contractCode = this.getParameterString("contractCode");
        	String creditPackageName = this.getParameterString("creditPackageName");
        	String dealCode = this.getParameterString("dealCode");
        	String idDeal = this.getParameterString("idDeal");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);
        	List<TCMmCreditPackageDTO> list = serviceContract.dealPackages(cooperorgCode,contractCode,creditPackageName);
        	model.addObject("idDeal", idDeal);
        	model.addObject("packageDto",null);
        	if (list != null && list.size() > 0) {
        		 model.addObject("packageDto",list.get(0));
        	}
        	List<DealDto> listAffiliation = creditDealService.getAffiliationByDealCode(dealCode);
        	model.addObject("affiliationValue",CollectionsUtils.isNotEmpty(listAffiliation)?listAffiliation.get(0).getRepaymentAffiliation():"");
        	//model.addObject("packageDto", list == null ? null : list.get(0));
        	model.setViewName("cims/creditDeal/updateTCMmCooperorgDeal");
        }else if("toBackLoanDetailUpdate".equals(operate)){//跳转至贷款交易修改页面
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String contractCode = this.getParameterString("contractCode");
        	String creditPackageName = this.getParameterString("creditPackageName");
        	String dealCode = this.getParameterString("dealCode");
        	String idDeal = this.getParameterString("idDeal");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);
        	List<TCMmCreditPackageDTO> list = serviceContract.dealPackages(cooperorgCode,contractCode,creditPackageName);
        	model.addObject("idDeal", idDeal);
        	//model.addObject("packageDto", list == null ? null : list.get(0));
        	//当包名不存在的时候   包名显示为空，不能提示pize异常 zhoupeng 20160628
        	if (list != null && list.size() > 0) {
       		 model.addObject("packageDto",list.get(0));
        	}
        	model.setViewName("cims/loanDealManage/updateTCMmLoanDeal");
        }
        
        return model;
    }
    
    /**
     * @author dell
     * @description:查询分页列表
     * @date 2015-01-06 11:21:31
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmContract")
    @ResponseBody
    public DataMsg queryListTCMmContract(HttpServletRequest request, TCMmContractDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmContractDTO> list = service.searchTCMmContractByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    @RequestMapping(value = "/returnContract")
    @ResponseBody
    public DataMsg returnContract(HttpServletRequest request, ContractAllDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	String contractCode = this.getParameterString("contractCode");
        List<ContractAllDto> list = serviceContract.returnContract(contractCode);
        dataMsg.setData(list);
        return dataMsg;
    }

    /**
     * @author dell
     * @description:新增
     * @date 2015-01-06 11:21:31
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmContract")
    @ResponseBody
    public DataMsg insertTCMmContract(HttpServletRequest request, TCMmContractDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmContractDTO)super.initDto(dto);
        	dto = (TCMmContractDTO)super.initInsertParam(dto);
            service.insertTCMmContract(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            Map<String,Object>map=this.makeJSONData(dto.getId());
            map.put("contractCode", dto.getContractCode());
            dataMsg.setData(map);
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author dell
     * @description:编辑
     * @date 2015-01-06 11:21:31
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmContract")
    @ResponseBody
    public DataMsg updateTCMmContract(HttpServletRequest request, TCMmContractDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmContractDTO)super.initDto(dto);
        	dto = (TCMmContractDTO)super.initUpdateParam(dto);
            service.updateTCMmContract(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author dell
     * @description:删除
     * @date 2015-01-06 11:21:31
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmContract")
    @ResponseBody
    public DataMsg deleteTCMmContract(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmContractByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author dell
     * @description:通过主键查询 其明细信息
     * @date 2015-01-06 11:21:31
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmContractDTO dto = service.queryTCMmContractByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    
}
